package self

import (
	"fmt"
	"io/ioutil"

	yaml "gopkg.in/yaml.v2"
)

// PostgresConfig postgreSQL datasource path config
type PostgresConfig struct {
	HostName    string `yaml:"HostName"`
	Port        int    `yaml:"Port"`
	User        string `yaml:"User"`
	Password    string `yaml:"Password"`
	Dbname      string `yaml:"Dbname"`
	SSLMode     string `yaml:"SSLMode"`
	SSLCert     string `yaml:"SSLCert"`
	SSLKey      string `yaml:"SSLKey"`
	SSLRootCert string `yaml:"SSLRootCert"`
}

// Config Self config
type Config struct {
	AuthKey  string          `yaml:"AuthKey"`
	Debug    bool            `yaml:"Debug"`
	Postgres *PostgresConfig `yaml:"Postgres"`
}

// GetConfigFromYaml get the self config from yaml
func GetConfigFromYaml(path string) Config {
	var conf Config
	dbuf, err := ioutil.ReadFile(path)
	if err != nil {
		panic("self config file open error")
	}
	err = yaml.Unmarshal(dbuf, &conf)
	if err != nil {
		panic("self config yaml unmarshal error:" + err.Error())
	}
	return conf
}

// GetDatasourceFromConfig the the postgreSQL datasource from config
func GetDatasourceFromConfig(conf Config) string {
	var pgDS string
	if conf.Postgres.SSLMode == "require" {
		pgDS = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=require sslcert=%s sslkey=%s sslrootcert=%s",
			conf.Postgres.HostName,
			conf.Postgres.Port,
			conf.Postgres.User,
			conf.Postgres.Password,
			conf.Postgres.Dbname,
			conf.Postgres.SSLCert,
			conf.Postgres.SSLKey,
			conf.Postgres.SSLRootCert,
		)
	} else {
		pgDS = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
			conf.Postgres.HostName,
			conf.Postgres.Port,
			conf.Postgres.User,
			conf.Postgres.Password,
			conf.Postgres.Dbname,
		)
	}
	return pgDS
}
